//
//  SchoolActivitiesViewController.m
//  AttendenceSys
//
//  Created by ld on 16/2/28.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "SchoolActivitiesViewController.h"

@interface SchoolActivitiesViewController ()

@end

@implementation SchoolActivitiesViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.strNavTitle = [NSString stringWithFormat:@"%@",_actInfo.subjectName];
    [self setRightText:@"发布"];
    _curPage = _totalPage = 1;
    [self initData];
    [self initView];
}

- (void)initData
{
    _actArr = [[NSMutableArray alloc] init];
    _actCopyArr = [[NSMutableArray alloc] init];
    _bRefresh = NO;
    
    [self getActivitiesInfo:_curPage];
}

//获取校园活动列表接口 http://121.42.185.124:8080/LawSchool/getSchoolActionList.action?userCode=xiaohu
- (void)getActivitiesInfo:(NSInteger)iPag
{
    NSString* refer = @"getSchoolActionList.action?";
    NSString* prefix = kASHttpUrl(refer);
    
    NSString* courseUrl = [NSString stringWithFormat:@"%@userCode=%@&page=%@&subjectId=%@", prefix,AS_APP_UserCode,[NSString stringWithFormat:@"%ld",(long)iPag],_actInfo.subjectId];
    
    [SVProgressHUD showWithStatus:@"获取学校活动" maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:courseUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        
        if (isSuccessRsp(jsonRsp))
        {
            _curPage = [[jsonRsp objectForKey:kASJsonMsgPage] integerValue];
            _totalPage = [[jsonRsp objectForKey:kASJsonMsgTotalPage] integerValue];
            NSArray* data = [jsonRsp objectForKey:kASJsonData];
           NSMutableArray* arr = [self parseSchoolActionListInfo:data];
            
            if (_bRefresh) {
                [_actArr removeObjectsInArray:_actCopyArr];
                _bRefresh = NO;
            }
            
            _actCopyArr = arr;
            
            [_actArr addObjectsFromArray:arr];
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
            
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
        [self reloadData];
    } failure:^(NSError *error) {
        [self reloadData];
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

- (NSMutableArray*)parseSchoolActionListInfo:(NSArray*)arr
{
    NSMutableArray* actArray = [[NSMutableArray alloc] init];
    for (unsigned int i = 0; i < [arr count]; i++)
    {
        ActivitiesInfo* actInfo = [[ActivitiesInfo alloc] init];
        NSDictionary* dic = [arr objectAtIndex:i];
        dic = [dic processDictionaryIsNSNull:dic];
        actInfo.actionArea = [dic objectForKey:@"actionArea"];
        actInfo.actionDesc = [dic objectForKey:@"actionDesc"];
        actInfo.actionPicture = [dic objectForKey:@"actionPicture"];
        actInfo.actionStatus = [dic objectForKey:@"actionStatus"];
        actInfo.actionTime = [dic objectForKey:@"actionTime"];
        actInfo.favorateNum = [dic objectForKey:@"favorateNum"];
        actInfo.actionTitle = [dic objectForKey:@"actionTitle"];
        actInfo.allCheckedNumber = [dic objectForKey:@"allCheckedNumber"];
        actInfo.allInvitedNumber = [dic objectForKey:@"allInvitedNumber"];
        actInfo.pushDate = [dic objectForKey:@"pushDate"];
        actInfo.imageUrlArr = [dic objectForKey:@"imageUrl"];
        
        actInfo.pkActionId = [dic objectForKey:@"pkActionId"];
        actInfo.portraitNum = [dic objectForKey:@"portraitNum"];
        
        actInfo.sponsor = [dic objectForKey:@"sponsor"];
        actInfo.userCode = [dic objectForKey:@"userCode"];
        actInfo.userName = [dic objectForKey:@"userName"];
        actInfo.voteNum = [dic objectForKey:@"voteNum"];
        actInfo.userPic = [dic objectForKey:@"userPic"];
        actInfo.isInvited = [dic objectForKey:@"isInvited"];
        actInfo.isCheck = [dic objectForKey:@"isCheck"];
        
        actInfo.sponsor = [actInfo.sponsor stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        actInfo.actionArea = [actInfo.actionArea stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        actInfo.actionDesc = [actInfo.actionDesc stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        actInfo.actionTitle = [actInfo.actionTitle stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        [actArray addObject:actInfo];
    }
    
    return actArray;
}

- (void)initView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-49-15);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[SchActivitiesSingeCell class] forCellReuseIdentifier:NSStringFromClass([SchActivitiesSingeCell class])];
    [_tableView registerClass:[SchActivitiesMutliCell class] forCellReuseIdentifier:NSStringFromClass([SchActivitiesMutliCell class])];
    [self.view addSubview:_tableView];
    
    _refresh=[[ASRefreshControl alloc] initWithScrollView:_tableView delegate:self];
    _refresh.topEnabled=YES;
    _refresh.bottomEnabled=YES;
}

- (void)refreshControl:(ASRefreshControl *)refreshControl didEngageRefreshDirection:(RefreshDirection)direction
{
    if (1 == _totalPage)
    {
        [self reloadData];
        return;
    }
    
    if (_curPage == _totalPage)
    {
        [SVProgressHUD showErrorWithStatus:@"没有更多的数据了"];
        [self reloadData];
        return;
    }
    
    if (direction==RefreshDirectionTop)
    {
        [self getActivitiesInfo:_curPage+1];
    }
    else if (direction==RefreshDirectionBottom)
    {
//        __weak typeof(self)weakSelf=self;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            __strong typeof(weakSelf)strongSelf=weakSelf;
//            [strongSelf reloadData];
//        });
         [self getActivitiesInfo:_curPage+1];
    }
}

- (void)reloadData
{
    if (self.refresh.refreshingDirection==RefreshingDirectionTop)
    {
        [self.refresh finishRefreshingDirection:RefreshDirectionTop];
    }
    else if (self.refresh.refreshingDirection==RefreshingDirectionBottom)
    {
        [self.refresh finishRefreshingDirection:RefreshDirectionBottom];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_actArr count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ActivitiesInfo* actInfo = [_actArr objectAtIndex:indexPath.row];
    
    SchActivitiesSingeCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SchActivitiesSingeCell class])];
    [cell setBackgroundColor:[UIColor clearColor]];
    [cell.headImageBtn setImageWithURL:actInfo.userPic placeholderImage:[UIImage imageNamed:@"portrait_default"]];
    
//    if (!actInfo.pushDate)
//    {
//        actInfo.pushDate = @"";
//        cell.timeLab.text = actInfo.pushDate;
//    }
//    else
//    {
//        cell.timeLab.text = [actInfo.pushDate substringToIndex:([actInfo.pushDate length]-3)];
//    }
    
    [cell updateDescLabelStatus:([actInfo.imageUrlArr count] > 0 ? YES : NO)];
    cell.timeLab.text = @"";
    cell.nameLab.text = actInfo.userName;
    cell.descLab.text = actInfo.actionDesc;
    cell.favorateNumLab.text = actInfo.favorateNum;
    
    cell.scanSignLab.text = [NSString stringWithFormat:@"报名参加人数: %@",actInfo.allInvitedNumber];
    cell.attendLab.text = [NSString stringWithFormat:@"扫码签到人数: %@",actInfo.allCheckedNumber];
    
    if (!actInfo.actionTitle)
    {
        actInfo.actionTitle = @"";
    }
    cell.actionTitleLab.text = [NSString stringWithFormat:@"活动标题: %@",actInfo.actionTitle];
    
    [cell initScrollView:actInfo.imageUrlArr];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.bgActView.tag = 100 + indexPath.row;
    [self addGestuerForCell:cell.bgActView];
   
    
//    [cell initActDetailInfoView];
//    cell.detailTime.text = [NSString stringWithFormat:@"时间：%@",actInfo.actionTime];
//    cell.sponsorLab.text = [NSString stringWithFormat:@"主办方：%@",actInfo.sponsor];;
//    cell.areaLab.text = [NSString stringWithFormat:@"地点：%@",actInfo.actionArea];
//    cell.voteNumLab.text = [NSString stringWithFormat:@"%@人感兴趣",actInfo.voteNum];
//    [cell initfavHeadScrollView:actInfo.imageUrlArr];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return singleCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AsActivityDetailViewController* detailViewCtrl = [[AsActivityDetailViewController alloc] init];
    detailViewCtrl.actDetailInfo = [_actArr objectAtIndex:indexPath.row];
    detailViewCtrl.delegate = self;
    detailViewCtrl.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailViewCtrl animated:YES];
}

- (void)rightButtonPressed:(id)sender
{
    AsActReleaseViewController* detailViewCtrl = [[AsActReleaseViewController alloc] init];
    detailViewCtrl.hidesBottomBarWhenPushed = YES;
    detailViewCtrl.delagate = self;
    detailViewCtrl.actCategoryId = _actInfo.subjectId;
    detailViewCtrl.actCategoryName = _actInfo.subjectName;
    [self.navigationController pushViewController:detailViewCtrl animated:YES];
}

//AsActReleaseViewControllerDelegate
- (void)refreshSchActVC
{
    _bRefresh = YES;
    [self getActivitiesInfo:_curPage];
}

- (void)refershActList:(ActivitiesInfo*)activistInfo
{
    if ([_actArr containsObject:activistInfo])
    {
        NSInteger index = [_actArr indexOfObject:activistInfo];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:index inSection:0]]
                              withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

//增加点击手势
- (void)addGestuerForCell:(UIView*)view
{
    for (UIGestureRecognizer *gesture in [view gestureRecognizers])
    {
        if ([gesture isKindOfClass:[UITapGestureRecognizer class]])
        {
            [view removeGestureRecognizer:gesture];
        }
    }

    UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBubble:)];
    tapGesture.numberOfTouchesRequired = 1;
    tapGesture.numberOfTapsRequired = 1;
    [view addGestureRecognizer:tapGesture];
}

// 点击气泡
- (void)tapBubble:(UITapGestureRecognizer *)tapGesture
{
    UIView* view = tapGesture.self.view;
    if (view)
    {
        AsActivityDetailViewController* detailViewCtrl = [[AsActivityDetailViewController alloc] init];
        detailViewCtrl.actDetailInfo = [_actArr objectAtIndex:view.tag-100];
        detailViewCtrl.delegate = self;
        detailViewCtrl.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailViewCtrl animated:YES];
    }
}

@end



